<?php

namespace Blog\App\Action;

use Hx\App;
use Hx\Event;
use Hx\Request;
use Hx\Response;
use Hx\View;

/**
 * 博客Action类
 * Class Blog
 * @package Blog\App\Action
 */
class Blog {

    /**
     * 显示一篇文章
     * @param string $key 文章关键字
     * @return string
     */
    public function one($key) {
        $blog = App::Model('Blog->getOne', array('nodeKey', $key));
        if (!$blog) {
            Response::sendRedirect('/error/404.html');
        }
        $viewData['blogData'] = $blog;
        $viewData['title'] = $blog->title;
        $viewData['commentData'] = App::Model('Comment->getTree', array($blog->id));
        Event::trigger('hit-update', array($blog->id));
        return View::display('blog.html', 2, $viewData);
    }

    /**
     * 博客评论处理
     * @param string $key 文章关键字
     * @return string
     */
    public function comment($key) {
        Response::setHeader('Content-Type', 'application/json;charset=UTF-8');
        $time = Request::getHttp('x_time');
        if ($time < 100 || (time() - $time) < 15) {
            return json_encode(array('result' => false, 'message' => '太快啦'));
        }
        $data = Request::post(true);
        if (!App::Model('Blog->checkKey', array($key, $data['node']))) {
            return json_encode(array('result' => false, 'message' => '文章错误'));
        }
        $res = App::Model('Comment->addComment', array($data));
        if ($res === false) {
            return json_encode(array('result' => false, 'message' => '评论失败'));
        }
        return json_encode(array('result' => true, 'comment' => $res));
    }
}